package srjava.server;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

import srjava.messages.CordinatorInfo;

public class RemoteCoordinator {
	CordinatorInfo coordinatorInfo;
	XmlRpcClient xmlRpcClient;
	
	public CordinatorInfo getCoordinatorInfo() {
		return coordinatorInfo;
	}

	public void setCoordinatorInfo(CordinatorInfo coordinatorInfo) {
		this.coordinatorInfo = coordinatorInfo;
	}

	public XmlRpcClient getXmlRpcClient() {
		return xmlRpcClient;
	}

	public void setXmlRpcClient(XmlRpcClient xmlRpcClient) {
		this.xmlRpcClient = xmlRpcClient;
	}

	public RemoteCoordinator() {
		this.coordinatorInfo = new CordinatorInfo();
		this.xmlRpcClient = new XmlRpcClient();
	}
	
	public void setCoordinator(CordinatorInfo info) {
		coordinatorInfo = info;
		XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
		try {
			config.setServerURL(new URL("http://"+coordinatorInfo.getAddress().getIp().toString()+":"+
					coordinatorInfo.getAddress().getSocet()));
		} catch (MalformedURLException e) {
			System.out.println("Nieprawidlowy adres");
			e.printStackTrace();
		}
		config.setReplyTimeout(5*1000);
		this.xmlRpcClient.setConfig(config);		
	}
	
	public RemoteCoordinator(CordinatorInfo coordinatorInfo) {
		this.coordinatorInfo = coordinatorInfo;
		this.xmlRpcClient = new XmlRpcClient();
	}

	public String sendMessage(String str) throws XmlRpcException {
		Object[] params = new Object[]{str};
		String result = (String) xmlRpcClient.execute("Server.MsgReceive", params);
		return result;
	}
}
